package repositorys

import (
	"io/ioutil"
	"path/filepath"
	"strings"
	"vala/tools"
)

type Site struct {
	Name     string
	Path     string
	Template Template
}

type Template struct {
	Name       string
	ServerName string // 域名
	ServerPath string // 路径
}

func (template *Template)fastCgiConfig() string {
	return `
location ~ \.php$ {
	fastcgi_split_path_info ^(.+\.php)(/.+)$;
	fastcgi_pass   127.0.0.1:9000;
	fastcgi_index  index.php;
	fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
	include        fastcgi_params;
}
`
}

func (template Template) ConsTemplateContent() string {
	content := ""
	switch template.Name {
	case "Laravel":
		content = `
    server {
        listen       80;
        server_name  {ServerName};
		root         {ServerPath};

		index index.html index.htm index.php;
		
		location / {
            try_files $uri $uri/ /index.php?$query_string;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
		
		{FastCGI}
    }
`
		content = strings.ReplaceAll(content, "{ServerName}", template.ServerName)
		content = strings.ReplaceAll(content, "{ServerPath}", template.ServerPath)
		content = strings.ReplaceAll(content, "{FastCGI}", template.fastCgiConfig())
	case "ThinkPHP5":
		content = `
    server {
        listen       80;
        server_name  {ServerName};
		root         {ServerPath};

		index index.html index.htm index.php;
		
		location / {
        	if ( !-e $request_filename) {
            	rewrite ^/(.*)$ /index.php/$1 last;
            	break;
        	} 
    	}

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        {FastCGI}
    }
`
		content = strings.ReplaceAll(content, "{ServerName}", template.ServerName)
		content = strings.ReplaceAll(content, "{ServerPath}", template.ServerPath)
		content = strings.ReplaceAll(content, "{FastCGI}", template.fastCgiConfig())
	default:
		filePath := filepath.Join(tools.GetAbsPath(template.ServerPath), "nginx.conf")
		byt, _ := ioutil.ReadFile(filePath)
		content = string(byt)
	}

	return content
}
